package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHUtil
import cn.com.kh.getProperty
import cn.com.kh.hst.ThreeDesUtil
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.json.JSONException
import org.json.JSONObject

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.time.Instant

/**
 *
 * @Title: aipHSTLogin
 * @Description:华盛证券 SSO统一登录接口 --内部接口
 * @author: cheih
 * @date 2021-07-06 10:28:00
 *
 */

public class aipHSTLogin implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTLogin.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        String getMethod = request.getMethod();
        log.debug("getMethod:" + getMethod);

        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        inData = URLDecoder.decode(inData, "UTF-8");
        log.debug("原始inData URLDecoder:" + inData);

        try {

            // 调用处理信息
            String loginId = "";
            String password = "";

            String[] allStrings = inData.split("&");
            if (allStrings != null && allStrings.length != 0) {

                for (String strings : allStrings) {

                    if (strings != null && strings.trim().length() != 0) {
                        String[] x = strings.split("=");
                        String S_key = x[0];
                        String S_value = strings.substring(strings.indexOf("=") + 1);

                        switch (S_key) {
                            case "loginId":
                                loginId = S_value;
                                break;
                            case "password":
                                password = S_value;
                                break;
                            default:
                                log.debug(S_key + "不在预设字段参数范围内!");
                        }
                    }

                }

            }

            log.debug("开始执行SSO用户账号验证...");

            long startTime = System.currentTimeMillis();
            String reJson = null;
            long endTime = 0;

            // 调用处理信息
            def remoteAddr = ThreeDesUtil.getIpAddr(request);//坐席ip
            log.debug("解析信息-" + "account: " + loginId + "password: " + password + "remoteAddr: " + remoteAddr);

            if (loginId == "" || loginId == null) {
                log.debug("account不存在");
                reJson = "{\"result\":\"-1\",\"message\":\"登录账号SSO验证异常\"}";
                return reJson;
            }

            //检查是否是本地管理员账号
            def localAdmin = eliteBean.chaxun_sql("Select Count(*) As Countnum From Staff Where Loginname = '" + loginId + "' And Staff_Id In (Select Staff_Id From Staffrolegroup Where Rolegroup_Id = 'SYSTEM') And (Stringfield3 = '" + password + "' Or Password = '" + password + "')", "dataSource");
            def localcount = localAdmin.get(0).get("Countnum");
            log.debug("检查是否是本地管理员账号:" + localcount);

            if (localcount <= 0) {
                log.debug("开始执行SSO用户账号验证...");

                //鉴权变量
                //String appid = "40001";
                //String appsecret = "zf7HxnNBg2o8fnCf611";
                String appid = getProperty.get("appid");
                String appsecret = getProperty.get("appsecret");

                //sign加密前后
                String signfront = "";
                String signafter = "";

                //操作员密码，3DES加密传输
                String passwordEncrypted = ThreeDesUtil.encode(appsecret, password);
                String passwordEncrypted1 = URLEncoder.encode(passwordEncrypted, "utf-8");
                log.debug("解析信息-" + "passwordEncrypted1: " + passwordEncrypted1);

                String sign_time = Instant.now().getEpochSecond();
                log.debug("解析信息-" + "passwordEncrypted: " + passwordEncrypted + "sign_time: " + sign_time);


                HashMap<String, String> paramHashMap = new HashMap<String, String>() {
                    {
                        put("account", loginId);
                        put("passwordEncrypted", passwordEncrypted);
                        put("remoteAddr", remoteAddr);
                        put("sign_time", sign_time);
                    }
                };

                HashMap<String, String> paramHashMap1 = new HashMap<String, String>() {
                    {
                        put("account", loginId);
                        put("passwordEncrypted", passwordEncrypted1);
                        put("remoteAddr", remoteAddr);
                        put("sign_time", sign_time);
                    }
                };

                log.debug("paramHashMap：" + paramHashMap);
                //自然排序 升序参数
                signfront = ThreeDesUtil.sortMap(paramHashMap, appid, appsecret);
                log.debug("sign加密MD5前：" + signfront);
                signafter = Util.getMD5Str(signfront);
                log.debug("sign加密MD5后：" + signafter);

                //拼接接口入参
                paramHashMap1.put("client_key", appid);
                paramHashMap1.put("sign", signafter);

                String injson = ThreeDesUtil.SplicingMap(paramHashMap1, "&");
                log.debug("injson:" + injson);

                outData = Loginin(eliteBean, injson, password, dataSourceID);
            } else {
                outData = "{\"result\":\"1\",\"message\":\"SYSTEM验证成功\",\"password\":\""+password+"\"}";
            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            outData = "{\"result\":\"-1\",\"message\":\"SSO登陆处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }
        log.debug("处理完成返回结果:" + outData);

        return outData;
    }

    //Loginin
    public static String Loginin(EliteBean eliteBean, String injson, String password, String dataSourceID) {

        long startTime = System.currentTimeMillis();
        log.debug("处理开始时间:" + startTime);

        long endTime = System.currentTimeMillis();

        String reJson = null;
        try {

            String doURL = getProperty.get("HSTURL");
            doURL = doURL + "/passport/admin/login";
            log.debug("doURL:" + doURL);

            Map<String, String> headMap = new HashMap<String, String>();
            headMap.put("Content-Type", "application/x-www-form-urlencoded");
            def getResult = Util.doHttpPostUseHead(doURL, injson, "UTF-8", 10000, 0, headMap);
            log.debug("getResult:" + getResult);

            //解析SSO返回信息
            JSONObject jsonObject = new JSONObject(getResult);
            String code = GetJV(jsonObject, "code");
            String result = GetJV(jsonObject, "result");

            JSONObject dataObject;
            log.debug("code:" + code);
            if (code == "00000") {
                dataObject = new JSONObject(result);
                log.debug("dataObject:" + dataObject);
                String loginname = GetJV(dataObject, "account");
                String userName = GetJV(dataObject, "userName");
                String token = GetJV(dataObject, "token");

                def countresult = eliteBean.chaxun_sql("select count(*) as countnum from staff where loginname = '" + loginname + "'", "dataSource");
                def count = countresult.get(0).get("countnum");

                String[] data1 = new String[1];
                if (count <= 0) {
                    String staff_id = KHUtil.getRandomString(6).toUpperCase();
                    data1[0] = "Insert Into Staff (Staff_Id, Staffname, Workstatus, Createdby, Createddate, Modifiedby, Modifieddate, Password, Loginname, Wrongpwdcount, Pwdmodify,Stringfield1,stringfield2,stringfield3) Values ('" + staff_id + "', '" + userName + "', 'ONLINE', 'HSTSSO', NOW(), 'HSTSSO', NOW(), '', '" + loginname + "', 0, NOW(),'" + token + "', NOW(),'" + password + "')";
                    log.debug("当前登陆人员暂时不存在与CC系统新建账号SQL:" + data1.toString());

                } else {

                    //data1[0] = "Update Staff Set Staffname = '" + userName + "', Pwdmodify = Now(), Wrongpwdcount = 0,Stringfield1 = '" + token + "',stringfield2=NOW(),stringfield3='" + password + "' Where Loginname = '" + loginname + "'";
                    data1[0] = "Update Staff Set Pwdmodify = Now(), Wrongpwdcount = 0,Stringfield1 = '" + token + "',stringfield2=NOW(),stringfield3='" + password + "' Where Loginname = '" + loginname + "'";
                    log.debug("当前登陆人员已经存在CC系统账号执行更新SQL:" + data1.toString());
                }

                int[] dataresult1 = eliteBean.updateBatch(data1, "dataSource");
                log.debug("CC系统登录信息表STAFF操作SQL结果:" + dataresult1.toString());


                //返回认证信息成功
                reJson = "{\"result\":\"1\",\"message\":\"SSO验证成功\",\"password\":\"\"}";
            } else {
                String msg = GetJV(jsonObject, "msg");
                reJson = "{\"result\":\"-1\",\"message\":\"SSO验证失败(" + msg + ")\"}";
            }

        } catch (JSONException e) {
            log.error("接口处理异常" + e.getMessage());
            // 失败返回
            reJson = "{\"result\":\"-1\",\"message\":\"登录账号SSO验证异常\"}";
        }

        return reJson;
    }


    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }


    // 非空校验isNull
    public static boolean isNull(String value) {

        boolean reFlag = true;
        if (value == "" || value.length() <= 0) {
            reFlag = true;
        } else {
            reFlag = false;
        }
        log.debug(reFlag);
        return reFlag;
    }

    // 非空校验isNullMSG
    public static String isNullMSG(String key, String value) {

        String reResult = "";
        if (value == "" || value.length() <= 0) {
            reResult = key + "必填字段;";
        }
        return reResult;
    }

}
